package models

import "gorm.io/gorm"

type News struct {
	gorm.Model
	Title    string `gorm:"type:varchar(100)" json:"title"`
	Time     string `gorm:"type:varchar(100)" json:"time"`
	Classify string `gorm:"type:varchar(100)" json:"classify"`
	Content  string `gorm:"type:varchar(255)" json:"content"`
	Author   string `gorm:"type:varchar(100)" json:"author"`
}

// 添加
func (u *News) Create() error {
	return DB.Create(&u).Error
}

// 列表展示
func (u *News) List(keyword string, page, pageSize int) (list []*News, err error) {
	db := DB
	if u.Model.ID > 0 {
		db = db.Where("type_id = ?", u.ID)
		return
	}
	err = DB.Where("title like ?", "%"+keyword+"%").Scopes(Paginate(page, pageSize)).Find(&list).Error
	return
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

// 修改
func (u *News) Update() error {
	return DB.Save(&u).Error
}

//删除

func (u *News) Del() error {
	return DB.Delete(&u).Error
}
